package com.example.function.integration.atomic;

import com.example.function.integration.annotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description：使用Semaphore、CountDownLatch协调线程，模拟高并发并验证正确性。使用AtomicInteger保证原子性。
 * @Author：fengcheng
 * @Date：2024/10/15 10:58
 */
@Slf4j
@ThreadSafe
public class AtomicExample1 {

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 表示同一时间并发多少个线程
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    // 获取许可证
                    semaphore.acquire();
                    add();
                    // 释放许可证
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                // 每次递减一个，表示一个请求已经被处理了
                countDownLatch.countDown();
            });
        }
        // 等待所有请求处理完毕，直到countDownLatch的计数为0，然后执行后面得代码
        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}", count.get());
    }

    private static void add() {
        count.incrementAndGet();
        // count.getAndIncrement();
    }
}
